package com.bwie.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bwie.dto.PageInfoVo;
import com.bwie.dto.ProdDto;
import com.bwie.es.EsProdVo;
import com.bwie.poi.StringUtils;
import com.bwie.utils.JwtsUtils;
import com.bwie.utils.R;
import org.checkerframework.checker.units.qual.A;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.domain.Prod;
import com.bwie.mapper.ProdMapper;
import com.bwie.service.ProdService;

import javax.servlet.http.HttpServletRequest;

@Service
public class ProdServiceImpl extends ServiceImpl<ProdMapper, Prod> implements ProdService{

    @Autowired
    private ProdMapper prodMapper;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Override
    public R saveProd(ProdDto prodDto) {
        // 初始化审计字段
        String token = request.getHeader("token");
        Integer idByToken = JwtsUtils.getIdByToken(token);

        Prod prod = new Prod();
        prod.setCreateBy(idByToken);
        prod.setCreateDate(new Date());
        prod.setDeleteFlag(0);

        // 参数传递
        BeanUtils.copyProperties(prodDto,prod);
        // 实现新增
        prodMapper.insert(prod);
        // 返回前端
        return R.OK();
    }

    @Override
    public R selectProdList(PageInfoVo pageInfoVo) {

        Page<Prod> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());

        Page<Prod> prodPage = prodMapper.selectProdList(page,pageInfoVo.getKeyWord());

        return R.OK(prodPage);
    }

    /**
     * @description: 从es当中查询商品数据
     * @author: Zero
     * @date: 2025/10/30 19:06
     * @param: [prodService]
     * @return: com.bwie.utils.R
     **/
    @Override
    public R selectProdListByEs(PageInfoVo pageInfoVo) {
        //1、 先定义分页组件
            //1.1 es 分页查询，页数索引是从 0 开始
        Integer num = 0 ;
        if (pageInfoVo.getPageNum() != null){
            num = pageInfoVo.getPageNum() - 1;
        }
        PageRequest pageRequest = PageRequest.of(num, pageInfoVo.getPageSize() == null ? 2 : pageInfoVo.getPageSize());
        //2、构建查询条件
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
            //2.1 根据商品状态进行精确查找
        if (pageInfoVo.getProdStatus() != null){
            boolQueryBuilder.must(QueryBuilders.termQuery("prodStatus",pageInfoVo.getProdStatus()));
        }
            //2.2 根据商品名称进行分词模糊匹配
        if (StringUtils.isNotEmpty(pageInfoVo.getProdName())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("prodName",pageInfoVo.getProdName()));
        }
            //2.3 根据创建时间进行范围匹配
        if(StringUtils.isNotEmpty(pageInfoVo.getBeginTime()) && StringUtils.isNotEmpty(pageInfoVo.getEndTime())){
            boolQueryBuilder.must(QueryBuilders.rangeQuery("createDate").timeZone("GMT+8")
                    .from(pageInfoVo.getBeginTime()).to(pageInfoVo.getEndTime()));
        }
            //2.4、构建排序
        FieldSortBuilder sortBuilder = SortBuilders.fieldSort("prodId").order(SortOrder.DESC);
        //3、高亮显示
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("prodName")
                .preTags("<font color = 'red'>")
                .postTags("</font>");
        //分组
        TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("group_status").field("prodStatus");
        //4、构建查询器A
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        nativeSearchQueryBuilder
                //分页插件
                .withPageable(pageRequest)
                //查询条件
                .withQuery(boolQueryBuilder)
                //排序
                .withSort(sortBuilder)
                //高亮显示
                .withHighlightBuilder(highlightBuilder)
                //分组
                .addAggregation(termsAggregationBuilder);
        //5、从es中查询数据
        SearchHits<EsProdVo> search = elasticsearchRestTemplate.search(nativeSearchQueryBuilder.build(), EsProdVo.class);
        return R.OK(search);
    }


}
